package app.services.auth;

import app.kit.AuthRedisKit;
import app.models.member.Member;
import com.google.common.base.Strings;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import goja.StringPool;
import goja.mvc.AjaxMessage;

import javax.servlet.http.HttpServletRequest;

/**
 * <p> </p>
 *
 * @author sogYF
 * @version 1.0
 * @since JDK 1.6
 */
public class AuthInterceptor implements Interceptor {

    public static final  String ATTR_UUID             = "rongli_uuid";
    public static final  String ATTR_AUTH             = "rongli_auth";
    public static final  String ATTR_MEMBER           = "rongli_member";
    public static final  String ATTR_MEMBER_PK        = "rongli_member_id";
    private static final String RONGLI_AUTHENTICATION = "rongli_authentication";


    @Override
    public void intercept(ActionInvocation ai) {

        final Controller controller = ai.getController();
        final HttpServletRequest request = controller.getRequest();


        AuthParam authParam = ai.getMethod().getAnnotation(AuthParam.class);
        boolean auth_flag = false, uuid_flag = true;
        if (authParam != null) {
            auth_flag = authParam.auth();
            uuid_flag = authParam.uuid();
        }
        if (uuid_flag) {
            final String uuid = request.getHeader(ATTR_UUID);
            if (Strings.isNullOrEmpty(uuid)) {
                controller.renderJson(AjaxMessage.FORBIDDEN);
                return;
            } else {
                controller.setAttr(ATTR_UUID, uuid);
            }
        }
        if (auth_flag) {
            final String rongliAuth = request.getHeader(RONGLI_AUTHENTICATION);
            if (Strings.isNullOrEmpty(rongliAuth)) {
                controller.renderJson(AjaxMessage.nologin());
                return;
            } else {
                // 从redis中获取用户信息，当用户登录的时候，存储信息到redis中
                Member member = AuthRedisKit.getMember(rongliAuth);
                if (member == null) {
                    controller.renderJson(AjaxMessage.nodata("Session expiration.", StringPool.EMPTY));
                    return;
                } else {
                    controller.setAttr(ATTR_MEMBER, member);
                    controller.setAttr(ATTR_MEMBER_PK, member.getNumber(StringPool.PK_COLUMN).intValue());
                    controller.setAttr(ATTR_AUTH, rongliAuth);
                }
            }
        }

        ai.invoke();


    }
}
